<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getProductReviews } from '@/api/order/orderReview'
import { getUserAccount } from '@/api/user'
import { formatTime } from '@/utils/format'

const productId = ref<number>(0)
const reviews = ref<any[]>([])
const activeTab = ref('all')
const loading = ref(false)
const pageNum = ref(1)
const pageSize = ref(5)
const hasMore = ref(true)
const total = ref(0)

// 评论分类
const reviewTabs = [
  { key: 'all', name: '全部' },
  { key: 'good', name: '好评' },
  { key: 'medium', name: '中评' },
  { key: 'bad', name: '差评' },
  { key: 'hasImage', name: '有图' }
]

// 计算各类型评论数量
const reviewCounts = computed(() => {
  const counts = {
    all: reviews.value.length,
    good: reviews.value.filter(review => review.rating >= 4).length,
    medium: reviews.value.filter(review => review.rating === 3).length,
    bad: reviews.value.filter(review => review.rating <= 2).length,
    hasImage: reviews.value.filter(review => review.images).length
  }
  return counts
})

// 获取商品评论
const fetchProductReviews = async (isLoadMore = false) => {
  if (!isLoadMore) {
    pageNum.value = 1
    reviews.value = []
  }
  
  try {
    loading.value = true
    const res = await getProductReviews(productId.value, {
      pageNum: pageNum.value,
      pageSize: pageSize.value
    })
    console.log(res)
    const reviewsData = res.rows || []
    total.value = res.total || 0
    
    // 获取每个评论的用户信息
    const reviewsWithUserInfo = await Promise.all(
      reviewsData.map(async (review: any) => {
        try {
          const userAccountRes = await getUserAccount(review.userId)
          return {
            ...review,
            userAvatar: userAccountRes.data?.userBase?.avatar || '/static/default-avatar.png',
            userName: userAccountRes.data?.userBase?.username || '匿名用户',
            userPoints: userAccountRes.data?.points || 0,
            userGender: userAccountRes.data?.userBase?.gender || 0
          }
        } catch (error) {
          console.error('获取用户信息失败：', error)
          return {
            ...review,
            userAvatar: '/static/default-avatar.png',
            userName: '匿名用户',
            userPoints: 0,
            userGender: 0
          }
        }
      })
    )
    
    if (isLoadMore) {
      reviews.value = [...reviews.value, ...reviewsWithUserInfo]
    } else {
      reviews.value = reviewsWithUserInfo
    }
    
    hasMore.value = reviews.value.length < total.value
  } catch (error) {
    console.error("获取商品评论失败：", error)
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (!hasMore.value || loading.value) return
  pageNum.value++
  fetchProductReviews(true)
}

// 预览图片
const previewReviewImage = (images: string[], current: number) => {
  uni.previewImage({
    urls: images,
    current: images[current]
  })
}

// 切换评论类型
const switchTab = (tab: string) => {
  activeTab.value = tab
  pageNum.value = 1
  reviews.value = []
  fetchProductReviews()
}

// 根据类型筛选评论
const filteredReviews = computed(() => {
  switch (activeTab.value) {
    case 'good':
      return reviews.value.filter(review => review.rating >= 4)
    case 'medium':
      return reviews.value.filter(review => review.rating === 3)
    case 'bad':
      return reviews.value.filter(review => review.rating <= 2)
    case 'hasImage':
      return reviews.value.filter(review => review.images)
    default:
      return reviews.value
  }
})

onLoad((options) => {
  if (options?.id) {
    productId.value = Number(options.id)
    fetchProductReviews()
  }
})
</script>

<template>
  <view class="review-list-page">
    <!-- 评论分类标签 -->
    <view class="review-tabs">
      <view 
        v-for="tab in reviewTabs" 
        :key="tab.key"
        class="tab-item"
        :class="{ active: activeTab === tab.key }"
        @click="switchTab(tab.key)"
      >
        <text>{{ tab.name }}</text>
        <text v-if="tab.key !== 'all'" class="tab-count">
          ({{ reviewCounts[tab.key as keyof typeof reviewCounts] }})
        </text>
      </view>
    </view>

    <!-- 评论列表 -->
    <view class="review-list">
      <view class="review-header">
        <text class="title">商品评价</text>
        <text class="count">({{ total }})</text>
      </view>
      <view v-if="loading && !reviews.length" class="loading">
        <text>加载中...</text>
      </view>
      <template v-else>
        <view v-if="filteredReviews.length > 0">
          <view v-for="review in filteredReviews" :key="review.id" class="review-item">
            <view class="review-user">
              <image 
                class="user-avatar" 
                :src="review.userAvatar" 
                mode="aspectFill"
              />
              <view class="user-info">
                <view class="user-name-row">
                  <text class="user-name">{{ review.userName }}</text>
                  <text class="user-gender" v-if="review.userGender === 1">♂</text>
                  <text class="user-gender female" v-else-if="review.userGender === 2">♀</text>
                  <text class="user-points">积分: {{ review.userPoints }}</text>
                </view>
                <view class="review-meta">
                  <text class="review-time">{{ formatTime(review.createTime) }}</text>
                  <view class="rating">
                    <text v-for="i in 5" :key="i" class="star" :class="{ 'active': i <= review.rating }">★</text>
                  </view>
                </view>
              </view>
            </view>
            <view class="review-content">
              <text class="review-text">{{ review.content }}</text>
              <view v-if="review.images" class="review-images">
                <image 
                  v-for="(image, index) in review.images.split(',')" 
                  :key="index"
                  :src="image"
                  mode="aspectFill"
                  class="review-image"
                  @click="previewReviewImage(review.images.split(','), index)"
                />
              </view>
            </view>
          </view>
          
          <!-- 加载更多 -->
          <view v-if="hasMore" class="load-more" @click="loadMore">
            <text v-if="loading">加载中...</text>
            <text v-else>加载更多</text>
          </view>
        </view>
        <view v-else class="no-review">
          <image src="/static/empty.png" mode="aspectFit" class="empty-image" />
          <text>暂无相关评价</text>
        </view>
      </template>
    </view>
  </view>
</template>

<style>
.review-list-page {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 20rpx;
}

.review-tabs {
  display: flex;
  background-color: #fff;
  padding: 20rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 100;
  backdrop-filter: blur(10px);
  background-color: rgba(255, 255, 255, 0.95);
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 16rpx 0;
  font-size: 28rpx;
  color: #666;
  position: relative;
  transition: all 0.3s ease;
}

.tab-item:active {
  transform: scale(0.95);
}

.tab-item.active {
  color: #1890ff;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background-color: #1890ff;
  border-radius: 2rpx;
  transition: all 0.3s ease;
}

.tab-count {
  font-size: 24rpx;
  color: #999;
  margin-left: 4rpx;
  background-color: #f5f5f5;
  padding: 2rpx 10rpx;
  border-radius: 20rpx;
}

.review-list {
  padding-bottom: 40rpx;
}

.loading {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}

.loading::after {
  content: '';
  width: 30rpx;
  height: 30rpx;
  border: 3rpx solid #f3f3f3;
  border-top: 3rpx solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.review-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.review-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 6rpx;
  height: 100%;
  background-color: #1890ff;
  opacity: 0;
  transition: all 0.3s ease;
}

.review-item:hover {
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.12);
}

.review-item:hover::before {
  opacity: 1;
}

.review-user {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
  border: 2rpx solid #f0f0f0;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.user-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.user-info {
  flex: 1;
}

.user-name-row {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 8rpx;
  flex-wrap: wrap;
}

.user-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  max-width: 200rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-gender {
  font-size: 24rpx;
  color: #1890ff;
  background-color: #e6f7ff;
  padding: 2rpx 10rpx;
  border-radius: 20rpx;
  transition: all 0.3s ease;
}

.user-gender.female {
  color: #eb2f96;
  background-color: #fff0f6;
}

.user-points {
  font-size: 24rpx;
  color: #ff4d4f;
  background-color: #fff1f0;
  padding: 2rpx 10rpx;
  border-radius: 20rpx;
  transition: all 0.3s ease;
}

.user-points:hover {
  transform: scale(1.05);
  box-shadow: 0 2rpx 8rpx rgba(255, 77, 79, 0.2);
}

.review-meta {
  display: flex;
  align-items: center;
  gap: 20rpx;
  flex-wrap: wrap;
}

.review-time {
  font-size: 24rpx;
  color: #999;
  background-color: #f5f5f5;
  padding: 2rpx 10rpx;
  border-radius: 20rpx;
}

.rating {
  display: flex;
  gap: 4rpx;
}

.star {
  font-size: 24rpx;
  color: #ddd;
  transition: all 0.3s ease;
}

.star.active {
  color: #ffb800;
  transform: scale(1.1);
  text-shadow: 0 2rpx 4rpx rgba(255, 184, 0, 0.3);
}

.review-content {
  margin-top: 20rpx;
}

.review-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
  background-color: #f8f9fa;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.review-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin-top: 20rpx;
}

.review-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  transition: all 0.3s ease;
  object-fit: cover;
}

.review-image:hover {
  transform: scale(1.02);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.no-review {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  margin-top: 20rpx;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
  opacity: 0.8;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0% { transform: translateY(0); }
  50% { transform: translateY(-10rpx); }
  100% { transform: translateY(0); }
}

.no-review text {
  font-size: 28rpx;
  color: #999;
  margin-top: 20rpx;
}

.load-more {
  text-align: center;
  padding: 30rpx;
  color: #666;
  font-size: 28rpx;
  background-color: #fff;
  border-radius: 16rpx;
  margin-top: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
}

.load-more:active {
  transform: scale(0.98);
  background-color: #f8f9fa;
}

.review-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 100rpx;
  z-index: 99;
  backdrop-filter: blur(10px);
  background-color: rgba(255, 255, 255, 0.95);
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.title::before {
  content: '';
  width: 6rpx;
  height: 32rpx;
  background-color: #1890ff;
  border-radius: 3rpx;
}

.count {
  font-size: 28rpx;
  color: #666;
  background-color: #f5f5f5;
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
  transition: all 0.3s ease;
}

.count:hover {
  background-color: #e6f7ff;
  color: #1890ff;
}
</style> 